package com.lhy.backend.domain.entity.user;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Data
@TableName("sys_user")
public class SysUser implements UserDetails, Serializable  {

    // 使用包装类。为什么呢？
    @TableId
    private Long id;
    private String username;
    private String nickname;
    private String email;
    private String mobile;
    // 用 Integer
    private Integer sex;
    private String avatar;
    private String password;
    private Integer status;
    private String creator;
    private String updater;
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
    private String remark;
    // 逻辑删除，MyBatis-Plus默认0是未删除，1是已删除
    @TableLogic
    private Integer deleted;

    //不初始化get的时候会报空指针 也调用不到方法
    // 角色信息
    @TableField(exist = false)
    private Set<SysRole> roleList = new HashSet<>();
    //权限的信息
    @TableField(exist = false)
    private Set<String> perms = new HashSet<>();




    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(ObjectUtils.isNotEmpty(perms)){
            return perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        }
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return status == 0;
    }

    @Override
    public boolean isAccountNonLocked() {
        return status == 0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return status == 0;
    }

    @Override
    public boolean isEnabled() {
        return status == 0;
    }
}
